package com.cherrypt.api.core.aspect;

import com.cherrypt.api.common.constant.TrackerConst;
import com.cherrypt.api.common.util.RequestUtils;
import com.cherrypt.api.core.controller.tracker.AnnounceController;
import com.cherrypt.api.core.util.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author intent
 * @date 2019/7/25 11:29
 * @about <link href='http://zzyitj.xyz/'/>
 */
@Component
@Aspect
public class AnnounceAspect {
    private static final Logger logger = LoggerFactory.getLogger(AnnounceAspect.class);

    @Pointcut("execution(* com.cherrypt.api.core.controller.tracker.AnnounceController.scrape(..))")
    public void scrape() {
    }

    @Pointcut("execution(* com.cherrypt.api.core.controller.tracker.AnnounceController.announce(..))")
    public void announce() {
    }


    @AfterReturning(value = "scrape() || announce()", returning = "result")
    public void log(JoinPoint joinPoint, String result) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String subResult = result.length() > 50 ? result.substring(0, 50) : result;
            logger.info("ip: {}, servletPath: {}, event: {}, up: {}, download: {}, left: {}, result: {}",
                    IPUtils.getIpAddr(request), request.getServletPath(),
                    RequestUtils.getQueryString(request.getQueryString(), TrackerConst.EVENT_PARAM),
                    RequestUtils.getQueryString(request.getQueryString(), TrackerConst.UPLOAD_PARAM),
                    RequestUtils.getQueryString(request.getQueryString(), TrackerConst.DOWNLOAD_PARAM),
                    RequestUtils.getQueryString(request.getQueryString(), TrackerConst.LEFT_PARAM), subResult);
        }
    }
}
